package com.iotproject.blogservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.iotproject.blogservice.entity.BlogType;
import com.iotproject.blogservice.entity.excel.BlogTypeData;
import com.iotproject.blogservice.service.BlogTypeService;
import com.iotproject.servicebase.exceptionhandler.GlobalException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class BlogTypeExcelListener extends AnalysisEventListener<BlogTypeData> {

    BlogTypeService blogTypeService;

    public BlogTypeExcelListener() {
    }

    public BlogTypeExcelListener(BlogTypeService blogTypeService) {
        this.blogTypeService = blogTypeService;
    }

    @Override
    public void invoke(BlogTypeData blogTypeData, AnalysisContext analysisContext) {
        if (blogTypeData == null) {
            throw new GlobalException(20001, "文件数据为空");
        }
        String title = blogTypeData.getTitle();
        Integer sort = blogTypeData.getSort();
        BlogType blogType = exitBlogType(blogTypeService, title);
        if (blogType == null) {
            blogType = new BlogType();
            blogType.setTitle(title);
            blogType.setSort(sort);
            blogTypeService.save(blogType);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    public BlogType exitBlogType(BlogTypeService blogTypeService, String title) {
        QueryWrapper<BlogType> blogTypeQueryWrapper = new QueryWrapper<>();
        blogTypeQueryWrapper.eq("title", title);
        BlogType blogType = blogTypeService.getOne(blogTypeQueryWrapper);
        return blogType;
    }

}
